package com.nuliji.tools.exception;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.nuliji.tools.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by gaojie on 2017/5/11.
 */

@ControllerAdvice
public class AllExceptionHandler implements HandlerExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(AllExceptionHandler.class);

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                     Exception ex) {
        ex.printStackTrace();
        logger.error(ex.toString());
        ModelAndView mv = new ModelAndView();
            /*  使用response返回    */
        response.setStatus(HttpStatus.OK.value()); //设置状态码
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
            response.getWriter().write(JSON.toJSONString( new Response(500, ex.getMessage(), null)));
        } catch (IOException e) {
            logger.error("与客户端通讯异常:"+ e.getMessage(), e);
        }

        return mv;
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object HandleValidationErrors(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        List<ObjectError> fieldErrors = result.getAllErrors();

        Map<String, String> errorMap = Maps.newHashMap();
        for(ObjectError fieldError : fieldErrors){
            logger.error("{}, error[{}], message: {}", fieldError.getObjectName(), JSON.toJSONString(fieldError.getArguments()), fieldError.getDefaultMessage());
            errorMap.put(fieldError.getObjectName(), fieldError.getDefaultMessage());
        }
        ObjectError objectError = fieldErrors.get(0);
        return new Response(400, objectError.getDefaultMessage(), null);
    }
}
